# coding: utf-8
# python3
import requests

from io import BytesIO
import numpy as np
from skimage import io
from PIL import Image


def getUrl(url):
    r = requests.get(url)
    return r.content


def resizeImage(fromFile, outFile, width=800, height=0):
    """

    param : fromFile 可以是文件名或者是流字符串格式如: BytesIO(buffer)
    """
    try:
        im = Image.open(fromFile)
        (w, h) = im.size #read image size
        height = height or (h * width // w) #calc height based on standard width
        out = im.resize((width, height), Image.ANTIALIAS) #resize image with high-quality
        out.save(outFile)
        return 1
    except Exception as e:
        return 0

class ImageBrinarization(object):
    """

    转二值化图像
    """
    def __init__(self):
        """
        :param img_path: 图片来源
        :param to_path: 保存路径
        """
        self.from_path = ''
        self.to_path = ''
        self.img = None
        self.img_mean = None

    def __toGrayScaleImage(self):
        """

        转灰度图
        """
        img = Image.open(self.from_path)
        self.img = img.convert("L")

    def __imageMean(self):
        """

        取图片灰度均值
        """
        img = io.imread(self.from_path)
        self.img_mean = np.mean(img)

    def __imageBinarization(self):
        """

        转二值化图片, 只有白和黑2种颜色
        """
        white, black = 255, 0
        self.img = self.img.point(lambda x: white if x > self.img_mean else black, '1')
        
    def convert(self, from_path, to_path):
        """

        将图片转成黑白图片
        """
        self.from_path = from_path
        self.to_path = to_path
        if all((self.from_path, self.to_path)):
            self.__toGrayScaleImage()
            if not self.img_mean:
                self.__imageMean()
            self.__imageBinarization()

            self.img.save(self.to_path)

imageBrinarization = ImageBrinarization()

def example():
    """

    例子
    """
    # example 1
    # imageBrinarization.convert('01.jpg', '01_b.jpg')

    # example 2
    url = 'https://upload-images.jianshu.io/upload_images/4955692-9b45948aead30492?imageMogr2/auto-orient/strip|imageView2/1/w/300/h/240'
    st = resizeImage(BytesIO(getUrl(url)), 'out1.jpg')
    print (st)


if __name__ == '__main__':
    example()